<template>
  <MkQueryContainer>
    <template #header>
      <MkForm ref="queryForm" :inline="true">
        <el-form-item label="关键字">
          <el-input @keyup.enter.native="search" v-model="searchParam.keyword" clearable />
        </el-form-item>
        <el-form-item>
          <MkButtonQuery @click="search"> </MkButtonQuery>
          <MkButtonAdd @click='add'> </MkButtonAdd>
        </el-form-item>
      </MkForm>
    </template>
    <MkTable :data="tableData" v-loading="loading" :span-method="handleSpanMethod" @row-dblclick="edit">
      <MkColumnIndex />
      <MkColumn prop="dingXueYiYuan" label="订血医院" :col="2" />
      <MkColumn prop="daLei" label="血液大类" />
      <MkColumn prop="yuJingZhiA" label="A型预警值" />
      <MkColumn prop="yuJingZhiB" label="B型预警值" />
      <MkColumn prop="yuJingZhiO" label="O型预警值" />
      <MkColumn prop="yuJingZhiAB" label="AB型预警值" />
      <MkColumnOption @show="edit" :isMore="false" />
    </MkTable>
    <MkPagination v-model:page="searchParam.page" v-model:pageSize="searchParam.pageSize" :total="total"
      @query="search" />
    <EditPage ref="editPageRef" @query="search" />
  </MkQueryContainer>
</template>

<script lang='ts' setup name="basConfig">
// 约血预警基础资料
import { BasYueXueYuJingApi, BasYueXueYuJingOutput } from '/@/api/bas/BasYueXueYuJing';
import { usePageQuery } from '/@/hooks/usePageQuery'

import EditPage from './edit.vue'

// 用于存储行合并信息的数组（值表示当前行需要合并的行数，0表示该行被合并）
const rowSpanList = ref<number[]>([]);
// 计算行合并逻辑函数
const calculateRowSpan = () => {
  rowSpanList.value = [];
  if (!tableData.value?.length) return;  // 空数据保护

  const startIndexes: Record<string, number> = {};  // 记录每个值的首次出现索引

  tableData.value.forEach((row, index) => {
    const currentValue = row.dingXueYiYuan;

    if (startIndexes[currentValue] === undefined) {
      // 首次出现该值：记录起始索引，当前行计数为1
      startIndexes[currentValue] = index;
      rowSpanList.value[index] = 1;
    } else {
      // 非首次出现：找到起始索引并累加计数，当前行计数为0
      const startIndex = startIndexes[currentValue];
      rowSpanList.value[startIndex]!++;  // 非空断言（已确保存在）
      rowSpanList.value[index] = 0;
    }
  });
};

const { searchParam, total, tableData, loading, search } = usePageQuery<BasYueXueYuJingOutput>(BasYueXueYuJingApi.page, calculateRowSpan)

const editPageRef = ref();

onMounted(() => {
  search();
})

const add = () => {
  editPageRef.value.open();
}

const edit = (row: BasYueXueYuJingOutput) => {
  editPageRef.value.open(row);
}

// 表格行合并方法（Element UI标准行合并逻辑）
const handleSpanMethod = ({ row, column, rowIndex, columnIndex }) => {
  // 仅对"订血医院"列生效（通过prop匹配）
  if (column.property === 'dingXueYiYuan') {
    const rowSpan = rowSpanList.value[rowIndex];
    return {
      rowspan: rowSpan,
      colspan: rowSpan > 0 ? 1 : 0  // 0列宽表示隐藏该行
    };
  }
  // 其他列不合并
  return { rowspan: 1, colspan: 1 };
};
</script>

<style lang='scss' scoped></style>